package com.gqb.video.myvideo.service.impl;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gqb.video.myvideo.contract.resp.QueryVideoBaseResp;
import com.gqb.video.myvideo.contract.resp.QueryVideoBaseResp.VodUrls;
import com.gqb.video.myvideo.service.IVideoParseApiService;

@Service
@Slf4j
public class BjVideoParseService implements IVideoParseApiService {

	@Override
	public List<QueryVideoBaseResp> videoParseToBj(String wd) {

		String query = HttpUtil.get("http://cj.bajiecaiji.com/inc/feifei3bjm3u8/index.php?wd=" + wd);

		JSONObject json = JSONObject.parseObject(query);

		if (json == null || json.isEmpty()) {
			return null;
		}

		Integer status = json.getInteger("status");
		if (status == null || status != 200) {
			log.error("===>> BjVideoParseService error:{}", json);
			return null;
		}

		List<QueryVideoBaseResp> list = new ArrayList<QueryVideoBaseResp>();

		QueryVideoBaseResp resp = new QueryVideoBaseResp();

		JSONArray data = json.getJSONArray("data");

		if (data.isEmpty()) {
			return null;
		}
		for (int i = 0; i < data.size(); i++) {
			resp = new QueryVideoBaseResp();
			JSONObject index = data.getJSONObject(i);
			resp.setListName(index.getString("list_name"));
			resp.setVodActor(index.getString("vod_actor"));
			resp.setVodArea(index.getString("vod_area"));
			resp.setVodLanguage(index.getString("vod_language"));
			resp.setVodContent(index.getString("vod_content"));
			resp.setVodName(index.getString("vod_name"));
			resp.setVodPic(index.getString("vod_pic"));
			resp.setVodRemarks(index.getString("vod_remarks"));
			resp.setVodYear(index.getString("vod_year"));

			resp.setVodList(getVodUrls(index.getString("vod_url")));

			list.add(resp);
		}

		return list;
	}

	public static List<VodUrls> getVodUrls(String vodUrl) {

		List<VodUrls> list = new ArrayList<QueryVideoBaseResp.VodUrls>();

		if (StringUtils.isBlank(vodUrl)) {
			return null;
		}

		String[] j = vodUrl.split("\r\n");
		if (j.length == 0) {
			return null;
		}

		VodUrls vod = null;

		for (int a = 0; a < j.length; a++) {
			String name = StringUtils.substringBefore(j[a], "$");
			String url = StringUtils.substringAfter(j[a], "$");

			vod = new VodUrls();
			vod.setName(name);
			vod.setVodUrl(url);
			list.add(vod);
		}

		return list;

	}

}
